#include "widget.h"
#include "ui_widget.h"
#include "card.h"
#include "log.h"
#include "bill.h"
#include "networkmanager.h"
#include <QTextCodec>
#include <QTimer>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonDocument>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    card = new Card;
    log = new Log;
    bill =new Bill;
    card->setWidget(this);
    log->setWidget(this);
    bill->setWidget(this);
    card->setLog(log);
    bill->setLog(log);
    log->setCard(card);
    bill->setCard(card);
    card->setBill(bill);
    log->setBill(bill);

    // 初始化 lcdNumber_carport（剩余停车位）的值为 8
    ui->lcdNumber_carport->display(8);

    networkManager = new NetworkManager(this);

    // 连接服务器：服务器地址是192.168.6.49 ，端口号是 8888
    //networkManager->connectToServer("192.168.6.49", 8888);
    networkManager->connectToServer("127.0.1.1", 8888);
    networkManager->sendMacId(0,888);
    //传递 networkManager 指针给 Card、Log、Bill对象
    card->setNetworkManager(networkManager);
    log->setNetworkManager(networkManager);
    bill->setNetworkManager(networkManager);

    // 连接信号和槽
    connect(networkManager, &NetworkManager::dataReceived, this, &Widget::onDataReceived);
    connect(networkManager, &NetworkManager::dataReceived, card, &Card::onDataReceived);
    connect(networkManager, &NetworkManager::dataReceived, log, &Log::onDataReceived);
    connect(networkManager, &NetworkManager::dataReceived, bill, &Bill::onDataReceived);
}

Widget::~Widget()
{
    delete ui;
    delete card;
    delete log;
    delete bill;
    delete networkManager;
}

//跳转到会员界面
void Widget::on_pushButton_card_clicked()
{
    card->show();
    this->hide();
}

//跳转到日志界面
void Widget::on_pushButton_log_clicked()
{
    log->show();
    this->hide();
}

//跳转到账单界面
void Widget::on_pushButton_bill_clicked()
{
    bill->show();
    this->hide();
}

// 发送入库车辆车牌
void Widget::on_pushButton_record_incar_clicked()
{
    // 获取各个编辑框中的文本信息
    QString incar = ui->lineEdit_record_incar->text();

    QString commandValue = "RECORD_INCAR";
    QString dataValue = incar;

    networkManager->sendCommand(commandValue,dataValue);
}

//发送出库车辆车牌
void Widget::on_pushButton_record_outcar_clicked()
{
    QString outcar = ui->lineEdit_record_outcar->text();

    QString commandValue = "RECORD_OUTCAR";
    QString dataValue = outcar;

    networkManager->sendCommand(commandValue,dataValue);
}

// 发送抬杆指令
void Widget::on_pushButton_lift_clicked()
{
    QString commandValue = "LIFT_BAR";
    QString dataValue = "lift";
    int macId = 666;

    networkManager->sendBarCommand(commandValue,dataValue,macId);
}

//发送一直抬杆指令
void Widget::on_pushButton_keeplift_clicked()
{
    QString commandValue = "LIFT_BAR";
    QString dataValue = "keeplift";
    int macId = 666;;

    networkManager->sendBarCommand(commandValue,dataValue,macId);
}

//发送落杆指令
void Widget::on_pushButton_lower_clicked()
{
    QString commandValue = "LIFT_BAR";
    QString dataValue = "lower";
    int macId = 666;

    networkManager->sendBarCommand(commandValue,dataValue,macId);
}

//处理接收到的数据
void Widget::onDataReceived(const QByteArray &data)
{
    // 调试
    qDebug() << "Received data:" << data;

    //因为有汉字无法显示，所以转为GBK编码
    // 1. 转为GBK解码
    QTextCodec *codec = QTextCodec::codecForName("GBK");
    QString gbkStr = codec->toUnicode(data);    //  GBK -> QString (UTF-16)

    // 2. 解析JSON
    QJsonDocument jsonDoc = QJsonDocument::fromJson(gbkStr.toUtf8());   //UTF-16 -> UTF-8 -> JSON
    if(jsonDoc.isNull())
    {
        qDebug() << "JSON 解析失败！";
        return;
    }

//    直接解析 JSON 数据
//    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
//    if (jsonDoc.isNull() || !jsonDoc.isObject())
//    {
//        qDebug() << "Failed to parse JSON data.";
//        return;
//    }

    QJsonObject jsonObj = jsonDoc.object();

    // 检查 command 字段
    if (jsonObj.contains("command"))
    {
        QString command = jsonObj["command"].toString();
        //抬杆操作
        if (command == "LIFT_BAR")
        {
            if (jsonObj.contains("data") && jsonObj.contains("mac_id") && this->isVisible())
            {
                QString result = jsonObj["data"].toString().trimmed();
                if (result == "lift")
                {
                    QMessageBox::information(nullptr, "提示", "已抬杆");
                }
                else if (result == "keeplift")
                {
                    QMessageBox::information(nullptr, "提示", "已抬杆");
                }
                else if (result == "lower")
                {
                    QMessageBox::information(nullptr, "提示", "已落杆");
                }
            }
        }
        //录入车牌
        else if (command == "RECORD_INCAR" || command == "RECORD_OUTCAR")
        {
            if (jsonObj.contains("data") && this->isVisible())
            {
                QMessageBox::information(nullptr, "提示", "已录入");
            }
        }
        //显示入库车牌
        else if (command == "LICENSE_NUM_IN")
        {
            //响应
            QString commandValue = "LICENSE_NUM_IN_ACK";
            QString dataValue = "succeed";
            networkManager->sendCommand(commandValue,dataValue);


            QString licenseNum = jsonObj.value("data").toString();
            ui->lineEdit_license_in->setText(licenseNum);
            // 设置定时器，只显示5s
            QTimer::singleShot(5000, [this]()
            {
                ui->lineEdit_license_in->clear();
            });
        }
        //显示出库车牌
        else if (command == "LICENSE_NUM_OUT")
        {
            //响应
            QString commandValue = "LICENSE_NUM_OUT_ACK";
            QString dataValue = "succeed";
            networkManager->sendCommand(commandValue,dataValue);

            //显示
            QString licenseNum = jsonObj.value("data").toString();
            ui->lineEdit_license_out->setText(licenseNum);
            // 设置定时器，只显示5s
            QTimer::singleShot(5000, [this]()
            {
                ui->lineEdit_license_out->clear();
            });
        }
        else if (command == "PARKING_SPACE") {
            //响应
            QString commandValue = "PARKING_SPACE_ACK";
            QString dataValue = "succeed";
            networkManager->sendCommand(commandValue,dataValue);

            if (jsonObj.contains("space") && jsonObj.contains("status"))
            {
                QString space = jsonObj["space"].toString();
                QString status = jsonObj["status"].toString();

                QString color;
                if (status == "occupancy")
                {
                    color = "rgb(69, 184, 255)";
                } else if (status == "unoccupancy")
                {
                    color = "rgb(193, 193, 193)";
                }

                if (!color.isEmpty())
                {
                    for (int i = 1; i <= 8; ++i)
                    {
                        QString currentSpace = QString("A%1").arg(i);
                        if (space == currentSpace)
                        {
                            QString labelName = QString("label_A%1").arg(i);
                            QLabel* label = this->findChild<QLabel*>(labelName);
                            if (label)
                            {
                                QString styleSheet = QString("background-color: %1;").arg(color);
                                label->setStyleSheet(styleSheet);
                            }
                        }
                    }
                }
            }
        }
    }
}

